package com.itheima.manager.service;

import com.itheima.manager.dao.SubwayDao;
import com.itheima.manager.domain.Subway;

import java.util.ArrayList;
import java.util.Collections;

public class SubwayService {
    SubwayDao dao = new SubwayDao();

    public ArrayList<Subway> selectSubways() {
        ArrayList<Subway> list = dao.selectSubways();
        boolean flag = false;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) != null) {
                flag = true;
            }
        }
        if (flag) {
            Collections.sort(list, (sub1, sub2) -> {
                if (sub1 != null & sub2 != null) {
                    return sub1.getId().compareTo(sub2.getId());
                } else {
                    return 0;
                }
            });
            return list;
        } else {
            return null;
        }
    }

    public boolean isExist(String id) {
        boolean flag = false;
        ArrayList<Subway> list = dao.selectSubways();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) != null & id.equals(list.get(i).getId())) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    public boolean addSubway(Subway sub) {
        boolean flag = false;
        int start = dao.selectSubways().size();
        dao.addSubway(sub);
        int end = dao.selectSubways().size();
        if ((end - start) == 1) {
            flag = true;
        }
        return flag;
    }

    public boolean deleteSubway(String id) {
        boolean flag = false;
        int start = dao.selectSubways().size();
        dao.deleteSubway(id);
        int end = dao.selectSubways().size();
        if ((start - end) == 1) {
            flag = true;
        }
        return flag;
    }


    public boolean updateSubway(String id, Subway sub) {
        boolean flag = false;
        if (id.equals(dao.updateSubway(id, sub).getId())) {
            flag = true;
        }
        return flag;
    }
}
